# -*- coding: utf-8 -*-

import base64
import urllib
import requests
import json
import subprocess

API_KEY = ""
SECRET_KEY = ""

def main():
    print(get_result())

def read_config(config_file_path, api_key, secret_key):
    """
    从配置文件中读取 API_KEY 和 SECRET_KEY
    :param file_path: 配置文件的路径
    :return: (API_KEY, SECRET_KEY)
    """

    try:
        with open(config_file_path, 'r') as file:
            for line in file:
                line = line.strip()
                if line.startswith("API_KEY"):
                    api_key = line.split('=')[1].strip().strip('"')
                elif line.startswith("SECRET_KEY"):
                    secret_key = line.split('=')[1].strip().strip('"')
    except FileNotFoundError:
        print(f"错误：文件 {config_file_path} 未找到。")
    except Exception as e:
        print(f"读取配置文件时发生错误：{e}")
    return api_key, secret_key

def get_result():
    url = "https://vop.baidu.com/server_api"
    # # 调用系统命令 pwd
    # result = subprocess.run(['pwd'], capture_output=True, text=True, check=True)
        
    # # 获取命令的输出
    # current_directory = result.stdout.strip()
        
    # # 打印当前工作目录
    # print(f"当前工作目录: {current_directory}")
    
    pcm_file_path = "../pcmfiles/receivedPcmData.pcm" #这个路径，看build的
    speech = get_file_content_as_base64(pcm_file_path, False)
    
    # 获取文件的字节数
    with open(pcm_file_path, "rb") as f:
        audio_data = f.read()
        lens = len(audio_data)
    
    payload = json.dumps({
        "format": "pcm",
        "rate": 16000,
        "channel": 1,
        "cuid": "L0dMNPDDeRM4wMOplUE2lkWbixgX76Ly",
        "speech": speech,
        "len": lens,
        "token": get_access_token()
    }, ensure_ascii=False)
    
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
    
    json_data = response.json()

    result_data = json_data.get("result")
    
    return result_data[0] if result_data else "无法识别"

def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded 
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    response = requests.post(url, params=params)
    if response.status_code == 200:
        return response.json().get("access_token")
    else:
        return None

if __name__ == '__main__':
    [API_KEY, SECRET_KEY] = read_config("../configs/pcmToTextConfig.txt", API_KEY, SECRET_KEY)
    main()
